package tjs.study.mini.springbootstartsmini.boot.web;

import lombok.SneakyThrows;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;

import java.io.File;
import java.util.Collections;
import java.util.Set;

/**
 * @author nicky
 * @date 2021/9/9 上午11:24
 */
public class TomcatServletWebServerFactory {

    private static final Set<Class<?>> NO_CLASSES = Collections.emptySet();

    @SneakyThrows
    public void createWebServer(ServletContextInitializer... initializers) {
        System.out.println("开始启动tomact....");
        //创建tomcat服务器
        Tomcat tomcatServer = new Tomcat();

        //构建Connector对象,此对象负责与客户端的连接.
        Connector con = new Connector("HTTP/1.1");
        //设置服务端的监听端口
        con.setPort(8083);
        //将Connector注册到service中
        tomcatServer.getService().addConnector(con);

        //读取项目路径,'/'可以加载静态资源
        StandardContext ctx = (StandardContext) tomcatServer.addWebapp(
                "/", new File("./").getAbsolutePath()
        );

        //禁止重新载入
        ctx.setReloadable(false);

        SpringServletContainerInitializer starter = new SpringServletContainerInitializer(initializers);
        //也可以配置 /META-INF/services/javax.servlet.ServletContainerInitializer文件
        ctx.addServletContainerInitializer(starter, NO_CLASSES);

        tomcatServer.start();
        System.out.println("Java语言创建Tomcat启动成功");
        //异步进行接收请求
        //tomcatServer.getServer().await();
    }

}
